import * as md5 from 'md5';
import DaTaoKeApi from '../../api/DaTaoKe';
import platform from '../../config/platform';
import BaseMall, { IQueryDetailParams, IQueryListParams } from './BaseMall';
import { GoodsDetail } from './typing/Mall';


export class TBMall extends BaseMall {
  private appKey = platform.daTaoKe.appKey;
  private appSecret = platform.daTaoKe.appSecret;
  private commonParams = {
    appKey: this.appKey,
    version: platform.daTaoKe.version,
  };

  async queryList(params: IQueryListParams<any>): Promise<GoodsDetail[]> {
    const queryParams = {
      ...this.commonParams,
      ...this.signature(),
      type: 1,
      pageId: params.page,
      pageSize: params.pageSize,
      keyWords: params.searchContent,
    } as const;

    return DaTaoKeApi.getInstance().superSearch(queryParams);
  }

  async queryDetail(params: IQueryDetailParams): Promise<GoodsDetail> {
    void params;
    // TODO
    return 1 as any;
  }

  private signature() {
    // appKey=5f81563803731&timer=1602317068725&nonce=234561&key=5f81563803731
    const timer = Date.now();
    const nonce = (Math.random() * 1000000).toFixed().padEnd(6, '0');

    const sign = md5(`appKey=${this.appKey}&timer=${timer}&nonce=${nonce}&key=${this.appSecret}`).toUpperCase();

    return {
      timer,
      nonce,
      signRan: sign,
    };
  }
}
